package com.third.bank.controller;

import com.third.bank.entity.User;
import com.third.bank.request.AddBalanceRequest;
import com.third.bank.request.ReduceBalanceRequest;
import com.third.bank.service.BalanceService;
import com.third.bank.service.UserService;
import com.third.bank.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.third.bank.entity.Balance;
import com.third.bank.request.AddBalanceRequest;
import com.third.bank.request.ReduceBalanceRequest;
import com.third.bank.service.BalanceService;
import com.third.bank.util.BaseResponse;
import com.third.bank.util.ErrorMessage;
import com.third.bank.util.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * 余额控制层
 */
@Api(value = "BalanceController", tags = {"账户交易模块"})
@RestController
@RequestMapping("/balance")
public class BalanceController {

    // 注入余额服务端
    @Autowired
    private BalanceService balanceService;

    @Autowired
    private UserService userService;

    @ApiOperation("存款")
    @PostMapping("add")
    public BaseResponse add(@ApiParam("存款请求对象") @RequestBody AddBalanceRequest addBalanceRequest) {
        return balanceService.addBalance(addBalanceRequest);
    }

    @ApiOperation("取款")
    @PostMapping("reduce")
    public BaseResponse reduce(@ApiParam("取款请求对象") @RequestBody ReduceBalanceRequest reduceBalanceRequest) {
        return balanceService.reduce(reduceBalanceRequest);
    }

    @GetMapping("/getBalance")
    public BaseResponse<BigDecimal> getBalanceByUserId(HttpServletRequest request) {

//        从token中取出用户id
        String token = request.getHeader("Authorization");
        long userId = Long.parseLong(JwtUtil.parseGetId(token));

        // 根据用户id查询余额
        LambdaQueryWrapper<Balance> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Balance::getUserId, userId);
        Balance balance = balanceService.getOne(queryWrapper);

        // 判断如果结果不为空则返回查询到的余额值，为空则添加错误信息
        if (balance != null) {
            return ResultUtils.success(balance.getBalance());
        } else {
            return ResultUtils.error(ErrorMessage.NOT_FOUND_ERROR);
        }
    }
}
